package com.guoli.sms.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * @author zhuxiaodong
 *
 */
public class DBTool {
	
	private DataSource ds = null;
	private static DBTool dbTool = new DBTool();
	
	private DBTool(){
	}
	public static DBTool newInstance(){
		if(dbTool==null){
			dbTool = new DBTool();
		}
		return dbTool;
	}
	public Connection getConnection(){
		String datasource = "java:comp/env/jdbc/guolisms";
		Connection conn = null;
		try {
			if(ds==null){
				Context ctx = new InitialContext();
				ds = (DataSource)ctx.lookup(datasource);
			}
			conn = ds.getConnection();
		} catch (NamingException e) {
			System.out.println("lookup datasource failed..."+e.getMessage());
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("get connection failed..."+e.getMessage());
			e.printStackTrace();
		}
		return conn;
	}
	public void closeConn(Connection conn){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public void closePstmt(PreparedStatement pstmt){
		if(pstmt!=null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					pstmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public void closeResultSet(ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
//				try {
//					rs.close();
//				} catch (SQLException e) {
//					e.printStackTrace();
//				}
			}
		}
	}
}
